<template>
  <BasicContainer>
    <FyCurd
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :permission="permissionList"
      :table-loading="tableLoading"
      :option="tableOption"
      :upload-after="uploadAfter"
      :upload-before="uploadBefore"
      :before-open="handleOpenBefore"
      :upload-error="uploadError"
      :before-close="beforeClose"
      @on-load="getList"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @row-del="rowDel">
      <template #menu="scope">
        <ElButton
          v-if="permissionList.downloadBtn"
          type="text"
          size="small"
          icon="el-icon-download"
          @click="download(scope.row, scope.index)">
          下载
        </ElButton>
        <ElButton
          v-if="scope.row.id !== -1"
          type="text"
          size="small"
          icon="el-icon-picture"
          @click="kkFileView(scope.row, scope.index)">
          预览
        </ElButton>
      </template>
    </FyCurd>
  </BasicContainer>
</template>

<script>
  import { delObj, fetchList } from '@/api/admin/sys-file'
  import { tableOption } from '@/const/crud/admin/sys-file'
  import { mapState } from 'vuex'
  import { openFile } from '@/api/file-view'

  export default {
    name: 'UploadPage',
    props: {
      uniqueCode: {
        type: String
      },
      model: {
        type: String
      },
      classify: {
        type: String
      },
      uploadPermissions: {
        type: Object,
        default: function () {
          return { addBtn: true, editBtn: true, delBtn: true, downloadBtn: true }
        }
      },
      viewType: {
        type: String
      }
    },
    data() {
      return {
        searchForm: {},
        tableData: [],
        form: {},
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption
      }
    },
    computed: {
      ...mapState('user', ['permissions']),
      permissionList() {
        return {
          addBtn: this.viewType === 'view' ? false : this.uploadPermissions.addBtn,
          delBtn: this.viewType === 'view' ? false : this.uploadPermissions.delBtn,
          editBtn: this.viewType === 'view' ? false : this.uploadPermissions.editBtn,
          downloadBtn: this.uploadPermissions.downloadBtn
        }
      }
    },
    methods: {
      getList(page, params) {
        if (this.$isBlank(params)) {
          params = { uniqueCode: this.$isBlank(this.uniqueCode) ? 'uniqueCode' : this.uniqueCode }
        } else {
          params.uniqueCode = this.uniqueCode
        }
        this.tableLoading = true
        fetchList(
          Object.assign(
            {
              descs: 'create_time',
              current: page.currentPage,
              size: page.pageSize
            },
            params,
            this.searchForm
          )
        )
          .then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      currentChange(current) {
        this.page.currentPage = current
      },
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 每页条数改变事件
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      handleOpenBefore(show, type) {
        this.tableOption.column[1].data = {
          uniqueCode: this.uniqueCode,
          classify: this.classify,
          model: this.model
        }
        window.boxType = type
        show()
      },
      refreshChange() {
        this.getList(this.page)
      },
      download: function (row, index) {
        this.$downBlobFile(`/admin/sys-file/${row.bucketName}/${row.fileName}`, this.searchForm, row.fileName)
      },
      rowDel: function (row, index) {
        this.$confirm(`是否确认删除ID为${row.id}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return delObj(row.id)
          })
          .then(data => {
            this.$message.success('删除成功')
            this.getList(this.page, this.from)
          })
      },
      uploadBefore(file, done, loading, column) {
        if (file.size > column.fileSize) {
          this.$message.error('文件大小不能超过10M！')
          loading()
          return
        }
        if (!this.vaildFileFormat(file)) {
          this.$message.error('限于bmp,png,gif,jpeg,jpg,doc,docx,xls,xlsx,zip,pdf格式！')
          loading()
          return
        }
        done()
      },
      vaildFileFormat(file) {
        // 限于bmp,png,gif,jpeg,jpg,doc,docx,xls,xlsx,zip,pdf格式。
        const format = ['bmp', 'png', 'gif', 'jpeg', 'jpg', 'doc', 'docx', 'xls', 'xlsx', 'zip', 'rar', 'pdf']
        const hasResult = false
        if (file.name.indexOf('.')) {
          const nameSuffix = file.name.split('.')
          const fileSuffix = nameSuffix[nameSuffix.length - 1]
          return format.includes(fileSuffix)
        }
        return hasResult
      },
      uploadError() {
        this.$message.success('上传失败')
        // console.log(error, column)
      },
      uploadAfter(res, done, loading, column) {
        this.getList(this.page, '')
        done()
        // this.$message.success('上传后的方法')
      },
      uploadPreview(file, column, done) {
        done() // 默认执行打开方法
        // this.$message.success('自定义查看方法,查看控制台')
      },
      beforeClose(done, type) {
        this.getList(this.page, '')
        done()
      },
      kkFileView(row, index) {
        openFile({ filename: row.original, format: row.type, name: row.fileName, bucketName: row.bucketName })
        // kkFilePreview(row)
      }
    }
  }
</script>
